package java_0593_synchronized;

public class SellTicket {
    public static void main(String[] args) {
//        SellTicket01 sellTicket01 = new SellTicket01();
//        SellTicket01 sellTicket02 = new SellTicket01();
//        SellTicket01 sellTicket03 = new SellTicket01();
//
//        sellTicket01.start();
//        sellTicket02.start();
//        sellTicket03.start();

//        SellTicket02 sellTicket02 = new SellTicket02();
//        new Thread(sellTicket02).start();
//        new Thread(sellTicket02).start();
//        new Thread(sellTicket02).start();

        SellTicket03 sellTicket03 = new SellTicket03();
        new Thread(sellTicket03).start();
        new Thread(sellTicket03).start();
        new Thread(sellTicket03).start();

    }
}

//使用同步机制
//使用Runnable接口
class SellTicket03 implements Runnable {
    private static int ticketNum = 1000;
    private boolean loop = true;

    public void setLoop(boolean loop) {
        this.loop = loop;
    }

    public synchronized void sell(){//在同一个时刻只能有一个线程进入
        if (ticketNum <= 0) {
            System.out.println("售票结束");
            setLoop(false);
            return;
        }
        //休眠50毫秒
        try {
            Thread.sleep(5);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("窗口" + Thread.currentThread().getName() + "售出一张票，还剩" + (--ticketNum));

    }

    @Override
    public void run() {
        while (loop) {
            sell();
//            //休眠50毫秒
//            try {
//                Thread.sleep(500);
//            } catch (InterruptedException e) {
//                throw new RuntimeException(e);
//            }
        }

    }
}

//使用Thread方式
class SellTicket01 extends Thread {
    private int ticketNum = 100;

    @Override
    public void run() {
        while (true) {
            if (ticketNum <= 0) {
                System.out.println("售票结束");
                break;
            }
            //休眠50毫秒
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("窗口" + Thread.currentThread().getName() + "售出一张票，还剩" + (--ticketNum));
        }

    }
}

//使用Runnable接口
class SellTicket02 implements Runnable {
    private static int ticketNum = 100;

    @Override
    public void run() {
        while (true) {
            if (ticketNum <= 0) {
                System.out.println("售票结束");
                break;
            }
            //休眠50毫秒
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("窗口" + Thread.currentThread().getName() + "售出一张票，还剩" + (--ticketNum));
        }

    }
}